const { customersModel } = require('./models/customersModel')

module.exports.getCustomers = async function(pageSize, cutPage, type = 'name', value = '') {
    let total = await customersModel.countDocuments({
        [type]: { $regex: value, $options: '$i' },
        deleteID: false
    }); //总条数
    let totalPage = Math.ceil(total / pageSize); //总页数
    let allCustomers = await customersModel.find({
        [type]: { $regex: value, $options: '$i' },
        deleteID: false
    }).populate({
        path: 'salesMenId'
    }).limit(pageSize - 0).skip((cutPage - 1) * pageSize);
    return { total, totalPage, allCustomers };
};
//是否已有该客户
module.exports.hasCustomers = async function(account, password, name, age, gender, phone, salesMenId) {
    const isHave = await customersModel.find({ account });
    return isHave
};
//添加客户
module.exports.addCustomers = async function(account, password, name, age, gender, phone, salesMenId) {
    const create = await customersModel.create({ account, password, name, age, gender, phone, salesMenId });
};
//删除客户
module.exports.delCustomers = async function(_id) {
    const result = await customersModel.updateOne({ _id }, { deleteID: true });
    return result.nModified
};
//获取单个
module.exports.getCustomerById = async function(_id) {
    const result = await customersModel.find({ _id }).populate({ path: 'salesMenId' });
    return result
};
//修改
module.exports.changeCustomers = async function(_id, account, password, name, age, gender, phone, salesMenId) {
    const result = await customersModel.updateOne({ _id }, { account, password, name, age, gender, phone, salesMenId });
    return result.nModified;
};
//根据销售员查找
module.exports.getCustomerBySalesMen = async function(salesMenId) {
    const result = await customersModel.find({ salesMenId });
    return result
};
module.exports.getCustomerBySalesMen = async function(salesMenId, pageSize, cutPage, type = 'name', value = '') {
    let total = await customersModel.countDocuments({
        [type]: { $regex: value, $options: '$i' },
        deleteID: false,
        salesMenId
    }); //总条数
    let totalPage = Math.ceil(total / pageSize); //总页数
    let allCustomers = await customersModel.find({
        [type]: { $regex: value, $options: '$i' },
        deleteID: false,
        salesMenId
    }).populate({
        path: 'salesMenId'
    }).limit(pageSize - 0).skip((cutPage - 1) * pageSize);
    return { total, totalPage, allCustomers };
};
//客户登录
module.exports.CustomersLogin = async function(account, password) {
    const result = await customersModel.find({ account, password });
    return result
};